package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.Region;
import cn.wolfcode.luowowo.query.RegionQuery;
import cn.wolfcode.luowowo.repository.RegionRepository;
import cn.wolfcode.luowowo.service.IRegionService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

//区域业务实现类
@Service
public class RegionServiceImpl implements IRegionService {
    //注入区域数据接口
    @Autowired
    private RegionRepository regionRepository;
    @Autowired
    private MongoTemplate mongoTemplate;

    //查询热门区域信息
    @Override
    public List<Region> hotRegion() {
        //按序号正序排序
        return regionRepository.findByIshotOrderBySequence(Region.STATE_HOT);
    }
    //根据区域id查询区域信息
    @Override
    public Region get(String id) {
        return regionRepository.findById(id).orElse(null);
    }

    //区域分页查询
    @Override
    public Page<Region> list(RegionQuery qo) {
        //创建条件对象
        Query query = new Query();
        //调用数据库工具类查询
        return DBHelper.PagingQuery(mongoTemplate, query, Region.class,qo.getPageable());
    }

    @Override
    public void save(Region region) {
        //防止调用者传了id覆盖了数据
        region.setId(null);
        regionRepository.save(region);
    }

    @Override
    public void update(Region region) {
        //此处前端是全量输入,不会有遗漏字段在全量更新时丢失
        regionRepository.save(region);
    }

    @Override
    public void delete(String id) {
        regionRepository.deleteById(id);
    }

    @Override
    public void changeHotValue(int hot, String id) {
        //防止全量更新时数据丢失
        //查询原数据
        Region region = get(id);
        //修改热门
        region.setIshot(hot);
        //更新数据
        update(region);
    }
}
